<template>
    <div>
      <!-- 面包屑导航区域 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片区域 -->
      <el-card>
        <!-- 搜索/添加区域 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <div>
              <el-input placeholder="请输入内容">
                <el-button slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <div>
              <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
            </div>
          </el-col>
        </el-row>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%" @close="addDialogClosed">
          <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="70px" status-icon>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <!-- 对话框底部区域 -->
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 表格区域：用户列表 -->
        <el-table :data="userTable" stripe border>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="phone" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态" width="180">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <!-- 编辑按钮 -->
              <el-button type="primary" icon="el-icon-edit" size="mini"></el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteById(scope.row.id)"></el-button>
              <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页部分 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageIndex"
          :page-sizes="[1, 5, 10]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      // 自定义校验规则
      // 邮箱验证
      var checkEmail = (rule, val, cb) => {
        const regEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        if (regEmail.test(val)) return cb()
        cb(new Error('请输入合法的邮箱'))
      }
      // 手机验证
      var checkMobile = (rule, val, cb) => {
        const regMobile = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/
        if (regMobile.test(val)) return cb()
        cb(new Error('请输入合法的手机号码'))
      }
      return {
        queryInfo: {
          // 当前页数
          pageIndex: 1,
          // 每页显示的条数
          pageSize: 5
        },
        // 总条数
        total: 0,
        // 用户数据
        userTable: [],
        // 控制对话框显示
        dialogVisible: false,
        addForm: {
          name: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 验证规则
        addRules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
            { validator: checkMobile, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      // 获取用户列表
      async getUserList() {
        const { data: res } = await this.$http.post('/api/userlist', this.queryInfo)
        this.userTable = res.data
        this.total = res.total
      },
      // 每页显示条数发生变化触发此事件
      handleSizeChange(val) {
        this.queryInfo.pageSize = val
        this.getUserList()
      },
      // 页码值发生变化触发此事件
      handleCurrentChange(val) {
        this.queryInfo.pageIndex = val
        this.getUserList()
      },
      // 重置表单
      addDialogClosed() {
        this.$refs.addFormRef.resetFields()
      },
      // 添加用户
      addUser() {
        // 添加用户预验证
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return false
          const { data: res } = await this.$http.post('/api/adduser', this.addForm)
          if (res.meta.status !== 201) {
            this.$msg.error('用户添加失败')
          }
          this.getUserList()
          this.$msg.success('用户添加成功')
          this.dialogVisible = false
        })
      },
      // 删除用户
      async deleteById(id) {
        // 弹框提示是否删除
        const res = await this.$cfm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err) // 捕获异常
  
        // 如果用户确认删除，则返回值为字符串 confirm
        // 如果用户取消了删除，则返回值为字符串 cancel
        if (res !== 'confirm') { return this.$msg.info('已取消删除') }
        // 如果确认了删除，则发起 axios 删除请求
        const { data: deleteres } = await this.$http.post('/api/deleteuser', id)
        if (deleteres.meta.status !== 200) return this.$msg.error('删除失败')
        this.getUserList()
        this.$msg.success('删除成功')
      }
    },
    created() {
      this.getUserList(
      )
    }
  }
  </script>
  
  <style lang="less" scoped>
  
  </style>